package com.example.xyr.myapplication.ui.im;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xyr.myapplication.Constant;
import com.example.xyr.myapplication.MyApp;
import com.example.xyr.myapplication.R;
import com.example.xyr.myapplication.adapter.ChatAdapter;
import com.example.xyr.myapplication.adapter.MyPagerAdapter;
import com.example.xyr.myapplication.fragment.EmoFragment;
import com.example.xyr.myapplication.utils.EmotionUtils;
import com.example.xyr.myapplication.utils.GlobalOnItemClickManagerUtils;
import com.example.xyr.myapplication.utils.ImageUtils;
import com.example.xyr.myapplication.utils.LogUtil;
import com.example.xyr.myapplication.utils.PermissionUtils;
import com.example.xyr.myapplication.utils.StringUtil;
import com.example.xyr.myapplication.view.RecordButton;
import com.example.xyr.myapplication.view.TitleBar;
import com.jrmf360.rplib.JrmfRpClient;
import com.jrmf360.tools.manager.CusActivityManager;
import com.jrmf360.tools.utils.SystemBarTintManager;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.dreamtobe.kpswitch.util.KPSwitchConflictUtil;
import cn.dreamtobe.kpswitch.widget.KPSwitchFSPanelLinearLayout;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;

/**
 * Created by ylcf on 2018/7/19.
 */

public class ChatActivity extends FragmentActivity implements View.OnClickListener {
    @BindView(R.id.chat_title)
    TitleBar chatTitle;
    @BindView(R.id.chat_recycler)
    RecyclerView chatRecycler;

    @BindView(R.id.chat_twinkling)
    TwinklingRefreshLayout chatTwinkling;
    @BindView(R.id.voice_text_switch_iv)
    ImageView voiceTextSwitchIv;
    @BindView(R.id.send_edt)
    EditText sendEdt;
    @BindView(R.id.send_voice_btn)
    RecordButton sendVoiceBtn;
    @BindView(R.id.plus_iv)
    ImageView plusIv;
    @BindView(R.id.iv_emo)
    ImageView ivEmo;
    @BindView(R.id.send_btn)
    TextView sendBtn;
    @BindView(R.id.sendMsgLayout)
    LinearLayout sendMsgLayout;
    @BindView(R.id.chat_redpackage)
    LinearLayout redPackage;
    @BindView(R.id.chat_iamge)
    LinearLayout chatIamge;
    @BindView(R.id.panel_content)
    LinearLayout panelContent;
    @BindView(R.id.panle_emo)
    LinearLayout panelEmo;
    @BindView(R.id.scvp_emo)
    ViewPager scvpEmo;
    @BindView(R.id.panel_root)
    KPSwitchFSPanelLinearLayout panelRoot;
    private String userId, otherUid;
    private ChatAdapter adapter;
    List<Message> msgData = new ArrayList<>();
    private Conversation mSingleCon;
    private UserInfo myInfo;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        ButterKnife.bind(this);
        tintStatusBar(0);
        CusActivityManager.getInstance().addActivity(this);
        JMessageClient.registerEventReceiver(this);
        init();
        initListener();
        initDate(savedInstanceState);
    }

    public void init() {
        adaptFitsSystemWindows(true);
        //不可上拉
        chatTwinkling.setEnableLoadmore(false);
        adapter = new ChatAdapter(this);
        chatRecycler.setAdapter(adapter);

        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
        if (permission == PackageManager.PERMISSION_DENIED) {
            String[] permissions = {Manifest.permission.RECORD_AUDIO};
            ActivityCompat.requestPermissions(this, permissions, 1);
        } else {
        }
    }

    public void initListener() {
        chatTitle.getIvBack().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        plusIv.setOnClickListener(this);
        ivEmo.setOnClickListener(this);
        redPackage.setOnClickListener(this);
        sendBtn.setOnClickListener(this);
        voiceTextSwitchIv.setOnClickListener(this);
        chatIamge.setOnClickListener(this);
        //初始化聊天键盘
        KPSwitchConflictUtil.attach(panelRoot, plusIv, sendEdt, ivEmo,
                new KPSwitchConflictUtil.SwitchClickListener() {
                    @Override
                    public void onClickSwitch(View v, boolean switchToPanel, int position) {
                        if (switchToPanel) {
                            sendEdt.clearFocus();
                            if (position == 1) {
                                panelContent.setVisibility(View.VISIBLE);
                                panelEmo.setVisibility(View.INVISIBLE);
                            } else {
                                panelContent.setVisibility(View.GONE);
                                panelEmo.setVisibility(View.VISIBLE);
                            }
                        } else {
                            sendEdt.requestFocus();
                        }
                    }
                });

        chatRecycler.setLayoutManager(new LinearLayoutManager(this));

        sendEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    panelRoot.setVisibility(View.GONE);
                }
            }
        });

        //点击空白收起弹框
        chatRecycler.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    hideKeyboard();
                    panelRoot.setVisibility(View.GONE);
                }

                return false;
            }
        });

        //edit输入监听
        sendEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    sendBtn.setVisibility(View.VISIBLE);
                    plusIv.setVisibility(View.INVISIBLE);
                } else {
                    sendBtn.setVisibility(View.INVISIBLE);
                    plusIv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //录音完成后监听
        sendVoiceBtn.setOnFinishedRecordListener(new RecordButton.OnFinishedRecordListener() {
            @Override
            public void onFinishedRecord(String audioPath, int duration) {
                try {
                    final Message msg = JMessageClient.createSingleVoiceMessage(otherUid, Constant.APPKEY, new File(audioPath), duration);
                    LogUtil.e("tag", "发送语音= " + msg.toJson());

                    adapter.addItem(msg);
                    chatRecycler.smoothScrollToPosition(adapter.getItemCount() - 1);
                    JMessageClient.sendMessage(msg);

                } catch (FileNotFoundException e) {
                    LogUtil.e("tag", "语音文件未找到");
                    e.printStackTrace();
                }
            }
        });

        chatTwinkling.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        chatTwinkling.finishRefreshing();
                    }
                }, 1000);
            }
        });
        //设置表情监听
        GlobalOnItemClickManagerUtils.getInstance(this).attachToEditText(sendEdt);
    }

    public void initDate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        userId = intent.getStringExtra(Constant.USER_ID);
        otherUid = intent.getStringExtra(Constant.OTHER_UID);
        JMessageClient.enterSingleConversation(otherUid, Constant.APPKEY);
        myInfo = JMessageClient.getMyInfo();
        LogUtil.e("tag", "userId = " + userId + " otherUid = " + otherUid);
        String otherNickName = intent.getStringExtra(Constant.OTHER_NICK_NAME);
        //创建单聊消息
        //用户昵称 设置title
        if (StringUtil.isNotEmpty(otherNickName)) {
            chatTitle.setTitle(otherNickName);
        }
        //获取历史聊天记录
        mSingleCon = JMessageClient.getSingleConversation(otherUid, Constant.APPKEY);
        LogUtil.e("tag", "singleConversation>>>>>>" + mSingleCon + "  otherUid = " + otherUid + " APPKEY=  " + Constant.APPKEY);
        if (mSingleCon != null) {
            List<Message> allMessage = mSingleCon.getAllMessage();
            if (allMessage != null) {
                for (Message msg : allMessage) {
                    msgData.add(msg);

                }
            }
        }
        //设置数据并滑到底部
        adapter.setmDatas(msgData);
        chatRecycler.scrollToPosition(adapter.getItemCount() - 1);
        initFragmentEmo();
    }

    /**
     * 初始化表情
     */
    private void initFragmentEmo() {
        List<Fragment> list = new ArrayList();
        EmoFragment emoFragment = new EmoFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(Constant.EMOTION_MAP_TYPE, EmotionUtils.EMOTION_CLASSIC_TYPE);
        emoFragment.setArguments(bundle);
        list.add(emoFragment);
        MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), list);
        scvpEmo.setAdapter(pagerAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_btn:  //发送消息
                String msg = sendEdt.getText().toString();
                if (StringUtil.isNotEmpty(msg)) {
                    sedJmsg(msg);
                }
                break;
            case R.id.voice_text_switch_iv:  //切换语音
                if (sendVoiceBtn.getVisibility() == View.VISIBLE) {
                    sendEdt.setVisibility(View.VISIBLE);
                    sendVoiceBtn.setVisibility(View.GONE);
                } else {
                    sendEdt.setVisibility(View.GONE);
                    sendVoiceBtn.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.chat_redpackage:  //发送红包
                JrmfRpClient.sendSingleEnvelopeForResult(this, otherUid, userId, MyApp.token, myInfo.getNickname(), myInfo.getAvatar(), Constant.CHAT_RED_PACKAGE);
                break;
            case R.id.chat_iamge:  //发送图片
                if (PermissionUtils.getInstance(this).sdPermission()) {
                    getImage();
                }
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        panelRoot.recordKeyboardStatus(getWindow());
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private void adaptFitsSystemWindows(final boolean isTranslucentStatusFitSystemWindowTrue) {
        if (isTranslucentStatusFitSystemWindowTrue
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            findViewById(R.id.panel_root).setFitsSystemWindows(true);
        }
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP
                && event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && panelRoot.getVisibility() != View.GONE) {
            KPSwitchConflictUtil.hidePanelAndKeyboard(panelRoot);
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    private void hideKeyboard() {
        InputMethodManager imm =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        sendEdt.clearFocus();
        imm.hideSoftInputFromWindow(sendEdt.getWindowToken(), 0);
    }

    Message sendMessage;

    private void sedJmsg(String text) {
        /**
         * 创建一条单聊文本消息，此方法是创建message的快捷接口，对于不需要关注会话实例的开发者可以使用此方法
         * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
         * 接口来创建消息
         *
         * @param username 聊天对象用户名
         * @param appKey   聊天对象所属应用的appKey
         * @param text     文本内容
         * @return 消息对象
         */
//        TextContent content = new TextContent(text);
        sendMessage = JMessageClient.createSingleTextMessage(otherUid, Constant.APPKEY, text);
        if (sendMessage != null) {
            sendMessage.setOnSendCompleteCallback(new BasicCallback() {
                @Override
                public void gotResult(int i, String s) {
                    if (i == 0) {
                        adapter.addItem(sendMessage);
                        LogUtil.e("tag", "发送消息 =  " + sendMessage.toString());
                        sendEdt.setText("");
                    } else {
                        LogUtil.e("tag", "文本消息发送失败==" + s);
                    }
                }
            });
            JMessageClient.sendMessage(sendMessage);
        }
    }

    //接收消息
    public void onEvent(MessageEvent event) {
        Message msg = event.getMessage();
        switch (msg.getContentType()) {
            case text:
                LogUtil.e("tag", "Message = " + msg.getDirect().toString() + "  " + msg.toString());
                //处理文字消息
                adapter.addItem(msg);
                chatRecycler.smoothScrollToPosition(adapter.getItemCount() - 1);
                break;
            case voice:
                LogUtil.e("tag", "语音Message = " + msg.getDirect().toString() + "  " + msg.toString());
                adapter.addItem(msg);
                chatRecycler.smoothScrollToPosition(adapter.getItemCount() - 1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 用户没有进行有效的设置操作，返回
        if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
            return;
        }
        switch (requestCode) {
            case Constant.CHAT_RED_PACKAGE:  //发送红包的回调
                String envelopesID = data.getStringExtra("envelopesID");
                String envelopeMessage = data.getStringExtra("envelopeMessage");
                String envelopeName = data.getStringExtra("envelopeName");
                String envelopeAmount = data.getStringExtra("envelopeAmount");
                String envelopeNumber = data.getStringExtra("envelopeNumber");
                int envelopeType = data.getIntExtra("envelopeType", 2);

                Map<String, String> map = new HashMap();
                map.put("envelopesID", envelopesID);
                map.put("envelopeMessage", envelopeMessage);
                map.put("envelopeName", envelopeName);
                map.put("envelopeType", envelopeType + "");
                map.put("envelopeAmount", envelopeAmount);
                map.put("envelopeNumber", envelopeNumber);
                map.put("customType", Constant.CUSTOM_REDPACKAGE);
                final Message singleCustomMessage = JMessageClient.createSingleCustomMessage(otherUid, Constant.APPKEY, map);
                if (singleCustomMessage != null) {
                    JMessageClient.sendMessage(singleCustomMessage);
                    adapter.addItem(singleCustomMessage);
                }
                break;
            case Constant.IMAGE_PICKER:
                List<Uri> mSelected = Matisse.obtainResult(data);
                LogUtil.e("tag", "mSelected: " + mSelected);
                if (mSelected != null && mSelected.size() > 0) {
                    for (Uri uri : mSelected) {
                        try {
                            final Message singleImageMessage = JMessageClient.createSingleImageMessage(otherUid, Constant.APPKEY, ImageUtils.Companion.getStringPath(this, uri));
                            singleImageMessage.setOnSendCompleteCallback(new BasicCallback() {
                                @Override
                                public void gotResult(int i, String s) {
                                    if (i == 0) {
                                        //消息发送成功
                                        adapter.addItem(singleImageMessage);
                                    } else {
                                        LogUtil.e("tag", "图片发送失败》》》》》");
                                    }
                                }
                            });
                            JMessageClient.sendMessage(singleImageMessage);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
        }
    }

    public String getOtherId() {
        return otherUid;
    }

    @Override
    protected void onDestroy() {
        msgData = null;
        super.onDestroy();
    }

    protected void tintStatusBar(int colorInt) {
        int color = colorInt == 0 ? R.color.my_my_red : colorInt;
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            int systemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
            systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            getWindow().getDecorView().setSystemUiVisibility(systemUiVisibility);
            getWindow().setStatusBarColor(getResources().getColor(color));
        } else if (Build.VERSION.SDK_INT >= 19) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(getResources().getColor(color));
        }

    }

    public void getImage() {
        //自定义方法的单选
        Matisse.from(ChatActivity.this)
                .choose(MimeType.ofAll())
                .countable(true)
                .maxSelectable(9)
                .addFilter(new GifSizeFilterM(320, 320, 5 * Filter.K * Filter.K))
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(Constant.IMAGE_PICKER);
    }
}
